import { useSearch, useSelect } from '@renderer/hooks';
import { Input } from 'antd';
import icon from '@renderer/assets/icon.png'
import { useEffect, useRef } from 'react';
import classNames from 'classnames'
import styles from './style.module.css'
import type { InputRef } from 'antd'

export function Search (): JSX.Element {
  const inputRef = useRef<InputRef | null>(null)
  const { value, handleChange, handleKeydown } = useSearch()
  const { snippets } = useSelect()

  useEffect(() => {
    const focusInput = () => {
      if (!inputRef.current || !inputRef.current.input) return

      inputRef.current.input.focus()
    }

    focusInput()

    window.api.onSearchShow(focusInput)
  }, [])

  return (
    <main className={styles.container}>
      <section
        className={classNames(
          'bg-primary	rounded-tl-lg flex items-center gap-1 flex-col flex-1 text-white',
          {
            'rounded-bl-lg': !snippets.length,
          },
        )}
      >
        <Input
          value={value}
          onChange={handleChange}
          onKeyDown={handleKeydown}
          placeholder='Hi, Snippets'
          ref={inputRef}
          variant="borderless"
          className='text-2xl font-bold text-white placeholder:text-t-secondary'
        />
        <a
          href="https://www.flaticon.com/free-icons/code"
          title="code icons"
          className='text-xs scale-75 text-t-secondary'
          target='_blank'
        >
          Code icons created by Freepik - Flaticon
        </a>
      </section>
      <section
        className={classNames(
          'bg-primary flex rounded-tr-lg pt-1',
          {
            'rounded-br-lg': !snippets.length,
          },
        )}
      >
        <img
          src={icon}
          className='w-8 h-8 cursor-pointer ml-2 mr-3'
          onClick={() => {
            window.api.closeWindow('search')
            window.api.openWindow('manager')
          }}
          onMouseDown={e => {
            e.stopPropagation()
          }}
        />
      </section>
    </main>
  )
}
